package com.ccm.demo.springbootsecurity.configuration;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration
@EnableTransactionManagement
public class DruidDBConfig {

	@Resource
	private Environment environment;
	@Bean
	@Primary
	public DataSource dataSource(){
		DruidDataSource dataSource=new DruidDataSource();
		dataSource.setDriverClassName(environment.getProperty("spring.datasource.driver-class-name"));
		dataSource.setUrl(environment.getProperty("spring.datasource.url"));
		dataSource.setUsername(environment.getProperty("spring.datasource.username"));
		dataSource.setPassword(environment.getProperty("spring.datasource.password"));
		dataSource.setInitialSize(Integer.valueOf(environment.getProperty("spring.datasource.initialSize")));
		dataSource.setMaxActive(Integer.valueOf(environment.getProperty("spring.datasource.maxActive")));
		dataSource.setMinIdle(Integer.valueOf(environment.getProperty("spring.datasource.minIdle")));
		dataSource.setMaxWait(Long.valueOf(environment.getProperty("spring.datasource.maxWait")));
		dataSource.setTimeBetweenEvictionRunsMillis(Long.valueOf(environment.getProperty("spring.datasource.timeBetweenEvictionRunsMillis")));
		dataSource.setMinEvictableIdleTimeMillis(Long.valueOf(environment.getProperty("spring.datasource.minEvictableIdleTimeMillis")));
		dataSource.setValidationQuery("SELECT 'x'");
		dataSource.setTestOnBorrow(true);
		dataSource.setTestOnReturn(false);
		dataSource.setTestWhileIdle(true);
		try {
			dataSource.setFilters("wall");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return dataSource;
	}
}
